//
//  TJTemplateController.m
//  BaoDian
//
//  Created by mac on 2024/7/17.
//

#import "TJTemplateController.h"
#import "SDCycleScrollView.h"
#import "HMSegmentedControl.h"
#import "TJTemplateChildController.h"
#import "TJTemplatePresent.h"

@interface TJTemplateController ()<SDCycleScrollViewDelegate, UIScrollViewDelegate>

@property (nonatomic, strong) NSMutableArray *types;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) NSMutableArray *listControllers;
@property (nonatomic, weak) HMSegmentedControl *segmentedControl;
@property (nonatomic, strong) NSArray *moduleList;
@property (nonatomic, strong) NSMutableDictionary *modulePool;
@property (nonatomic, assign) BOOL isNeedRebuildModule;
@property (nonatomic, weak) SDCycleScrollView *cycleScrollView;

@end

@implementation TJTemplateController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    SDCycleScrollView *cycleScrollView =  [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(16, KNavBarHight + 3, KScreenWidth - 32, 130) delegate:self placeholderImage:nil];
    cycleScrollView.addCornerRadius(12);
    cycleScrollView.backgroundColor = UIColor.tj_backgroundColor;
    cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;

    _cycleScrollView = cycleScrollView;
    [self.view addSubview:cycleScrollView];
    
    [self getTypesComplete:^(NSArray *moduleList) {
        self.moduleList = moduleList;
        [self buildDataWithTypes:moduleList];
    }];
    
    [self loadData];
}

- (void)loadData {
    [TJTemplatePresent loadCarouselDataComplete:^(NSArray * _Nonnull datas, NSError * _Nullable error) {
        NSMutableArray *arr = [NSMutableArray array];
        for (NSDictionary *dict in datas) {
            [arr addObject:dict[@"imgUrl"]];
        }
        self.cycleScrollView.imageURLStringsGroup = arr;
    }];

}

- (void)addSegmentedControl {
    
    [_segmentedControl removeFromSuperview];
    
    if (self.types.count == 0) {
        return;
    }
    
    NSMutableArray *segmentedDatas = @[].mutableCopy;
    for (NSDictionary *dict in self.types) {
        [segmentedDatas addObject:dict[@"name"]];
    }
    
    HMSegmentedControl *segmentedControl = [[HMSegmentedControl alloc] initWithSectionTitles:segmentedDatas];
    segmentedControl.segmentEdgeInset = UIEdgeInsetsMake(0, 13, 0, 13);
    segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleTextWidthStripe;
    segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationBottom;
    segmentedControl.selectionIndicatorHeight = 1;
    segmentedControl.selectionIndicatorEdgeInsets = UIEdgeInsetsMake(0, 0, -3, 0);
    segmentedControl.selectionIndicatorColor = UIColorMake(0x2978F0);
    segmentedControl.segmentWidthStyle = HMSegmentedControlSegmentWidthStyleDynamic;
    segmentedControl.verticalDividerEnabled = NO;
    segmentedControl.backgroundColor = UIColor.clearColor;
    [segmentedControl setTitleTextAttributes:@{
        NSForegroundColorAttributeName : UIColor.tj_8D9298Color,
        NSFontAttributeName : UIFontMake(16)
    }];
    [segmentedControl setSelectedTitleTextAttributes:@{
        NSForegroundColorAttributeName : UIColor.whiteColor,
        NSFontAttributeName : UIFontMediumMake(16)
    }];
    [segmentedControl addTarget:self action:@selector(segmentedControlChangedValue:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:segmentedControl];
    [segmentedControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(10);
        make.top.equalTo(self.cycleScrollView.mas_bottom).offset(12);
        make.height.offset(32);
    }];
    self.segmentedControl = segmentedControl;
}

- (void)buildDataWithTypes:(NSArray *)types {
    
    if (types.count) {
        [self.types removeAllObjects];
    }
    
    [types enumerateObjectsUsingBlock:^(NSDictionary *  _Nonnull dict, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableDictionary *object = [NSMutableDictionary dictionaryWithDictionary:dict];
        TJTemplateChildController *childController = [self.modulePool objectForKey:toString(dict[@"type"])];
        if (childController) {
            [object setValue:childController forKey:@"controller"];
        } else {
            [object setValue:[[TJTemplateChildController alloc] init] forKey:@"controller"];
        }
        [self.types addObject:object];
    }];
    
    [self addSegmentedControl];
    
    [_scrollView removeFromSuperview];
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, self.cycleScrollView.tj_MaxY + 40, KScreenWidth, KScreenHeight - (self.cycleScrollView.tj_MaxY + 44) - TabBarHeight)].addTo(self.view);
    _scrollView.pagingEnabled = YES;
    _scrollView.bounces = NO;
    _scrollView.delegate = self;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.contentSize = CGSizeMake(_scrollView.frame.size.width * self.types.count, _scrollView.frame.size.height);
    
    if (_isNeedRebuildModule) {
        [self.childViewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [obj removeFromParentViewController];
        }];
    }
    
    [self.types enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        TJTemplateChildController *listController = obj[@"controller"];
        listController.type = obj[@"type"];
        [self addChildViewController:listController];
        [self.scrollView addSubview:listController.view];
        listController.view.frame = CGRectMake(KScreenWidth * idx, 0, KScreenWidth, _scrollView.tj_height);
        [self.modulePool setObject:listController forKey:toString(obj[@"type"])];
        [self.listControllers addObject:listController];
    }];
    
    if (self.types.count > 1) {
        [self.segmentedControl setSelectedSegmentIndex:0 animated:NO];
        [self loadDataWithIndex:0];
    }
    
}

- (void)segmentedControlChangedValue:(HMSegmentedControl *)segmentedControl {
    [self.scrollView setContentOffset:CGPointMake(KScreenWidth * segmentedControl.selectedSegmentIndex, 0)];
    [self loadDataWithIndex:segmentedControl.selectedSegmentIndex];
}

- (void)loadDataWithIndex:(NSInteger)index {
    if (index >= self.listControllers.count) return;
    TJTemplateChildController *listController = [self.listControllers objectAtIndex:index];
    [listController loadData];
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    CGFloat pageWidth = scrollView.frame.size.width;
    NSInteger page = scrollView.contentOffset.x / pageWidth;
    
    [self.segmentedControl setSelectedSegmentIndex:page animated:YES];
    [self loadDataWithIndex:page];
}

- (void)getTypesComplete:(void (^)(NSArray *moduleList))complete {
//    NSArray *moduleList = [USERDEFAULTS objectForKey:moduleListKey];
//    if (moduleList) {
//        complete(moduleList);
//    } else {
        [TJTemplatePresent loadIndustryListComplete:^(NSArray * _Nonnull datas, NSError * _Nullable error) {
            complete(datas);
        }];
//    }
}

- (NSMutableArray *)types {
    if (!_types) {
        _types = [NSMutableArray array];
    }
    return _types;
}

- (NSMutableDictionary *)modulePool {
    if (!_modulePool) {
        _modulePool = [NSMutableDictionary dictionary];
    }
    return _modulePool;
}

- (NSMutableArray *)listControllers {
    if (!_listControllers) {
        _listControllers = [NSMutableArray array];
    }
    return _listControllers;
}

- (void)rebuildModule {
    
    NSArray *newsModuleList = [USERDEFAULTS objectForKey:moduleListKey];
    if (newsModuleList.count == 0) return;
    
    if (newsModuleList.count > 0 && self.moduleList.count == newsModuleList.count) {
        
        NSMutableString *originalString = [NSMutableString string];
        for (NSDictionary *dict in self.moduleList) {
            [dict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
                [originalString appendFormat:@"%@%@",obj, obj];
            }];
        }
        NSMutableString *string = [NSMutableString string];
        for (NSDictionary *dict in newsModuleList) {
            [dict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
                [string appendFormat:@"%@%@",obj, obj];
            }];
        }
        if (![string isEqualToString:originalString]) {
            [self buildDataWithTypes:newsModuleList];
        }
    } else {
        [self buildDataWithTypes:newsModuleList];
    }
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (self.moduleList.count == 0) {
        [TJTemplatePresent loadIndustryListComplete:^(NSArray * _Nonnull datas, NSError * _Nullable error) {
            self.moduleList = datas;
            [self buildDataWithTypes:datas];
        }];
    }
    if (self.cycleScrollView.imageURLStringsGroup.count == 0) {
        [self loadData];
    }
}


- (BOOL)hiddenNavigationBar {
    return YES;
}

@end
